package com.book.book.Controller;

import com.book.book.domain.User;
import com.book.book.service.UserService;
import com.book.book.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 用户登录接口
     * @param user 包含 username 和 userpassword
     * @return 登录结果及token
     */
    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        User foundUser = userService.login(user.getUsername(), user.getUserpassword());

        if (foundUser != null) {
            String token = JwtUtils.getToken(foundUser.getUsername());
            result.put("code", 200);
            result.put("msg", "登录成功");
            result.put("token", token);
            result.put("username", foundUser.getUsername());
            result.put("isAdmin", foundUser.getIsadmin()); // 返回用户是否为管理员
        } else {
            result.put("code", 400);
            result.put("msg", "用户名或密码错误");
        }
        return result;
    }

    @PostMapping("/register")
    public Map<String, Object> register(@RequestBody User user) {
        Map<String, Object> result = new HashMap<>();
        try {
            // 检查用户名是否已存在
            User existingUser = userService.findByUsername(user.getUsername());
            if (existingUser != null) {
                result.put("code", 409); // 409 Conflict，表示冲突（资源已存在）
                result.put("msg", "用户名已存在");
                return result;
            }

            // 注册用户，默认设置为普通用户 (isAdmin = 0)
            user.setIsadmin(0); // 确保新注册的用户是普通用户
            boolean success = userService.register(user);

            if (success) {
                result.put("code", 200);
                result.put("msg", "注册成功");
            } else {
                result.put("code", 500);
                result.put("msg", "注册失败，请稍后再试");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "服务器内部错误: " + e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}
